package com.abe.signature.print;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.Toast;

import com.itextpdf.text.pdf.BaseFont;

import java.io.File;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

public class PrintHelper {
    //文件系统根目录
    private static String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    //存储目录
    private static String printPath = dirPath + File.separator + "abeframe" + File.separator + "print";
    //字体安装文件与打印插件存储目录
    private static String utilPath = printPath + File.separator + "utils";

    private static final String PRINT_PACKAGE_1 = "com.dynamixsoftware.printershare.amazon";
    private static final String PRINT_PACKAGE_2 = "com.dynamixsoftware.printershare";
    // 打印所需apk的文件名
    private static final String PrintAPK = "PrinterShare_android8.0.apk";
    // 打印所需字体文件名
    private static final String PrintFont = "FZSYJW.TTF";

    private static Reference<PrintHelper> helperReference;
    private Context context;

    public static PrintHelper getInstance(Context context) {
        if (helperReference == null)
            helperReference = new WeakReference<>(new PrintHelper(context));
        return helperReference.get();
    }

    private PrintHelper(Context context) {
        this.context = context;
    }

    public void printPDF(final String filepath) {
        //检查文件名
        if (TextUtils.isEmpty(filepath)) {
            Toast.makeText(context, "打印路径为空", Toast.LENGTH_SHORT).show();
            return;
        }
        int dotIndex = filepath.lastIndexOf(".");
        if (dotIndex < 0) {
            Toast.makeText(context, "文件路径有误", Toast.LENGTH_SHORT).show();
            return;
        } else {
            String tem = filepath.substring(dotIndex);
            if (!tem.equals(".pdf")) {
                Toast.makeText(context, "文件路径有误", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        //检查打印插件安装
        boolean isApp = checkAPP(context, PRINT_PACKAGE_1) || checkAPP(context, PRINT_PACKAGE_2);
        boolean font = checkFont();
        if (isApp && font) {
            //直接打印
            CallPrint(filepath);
        }
        if (isApp && !font) {
            //安装字体// 安装字体、打印APK
            AssetsFileUtils.getInstance(context)
                    .copyAssetsToSD("print", "abeframe/print/utils")
                    .setFileOperateCallback(new AssetsFileUtils.FileOperateCallback() {
                        @Override
                        public void onSuccess() {
                            BaseFont baseFont = creatBaseFont();
                            //调用打印
                            if (baseFont != null) {
                                CallPrint(filepath);
                            }
                        }

                        @Override
                        public void onFailed(String error) {

                        }
                    });
        }
        if (!isApp) {
            InstallationTipsDialog(context);
        }
    }

    private void CallPrint(String filepath) {
        ComponentName comp = new ComponentName(
                "com.dynamixsoftware.printershare",
                "com.dynamixsoftware.printershare.ActivityPrintPDF");
        Intent intent = new Intent();
        intent.setComponent(comp);
        intent.setAction("android.intent.action.VIEW");
        intent.setType("application/pdf");
        intent.setData(Uri.fromFile(new File(filepath)));
        context.startActivity(intent);
    }

    /**
     * 检查应用是否存在
     */
    private static boolean checkAPP(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            context.getPackageManager()
                    .getApplicationInfo(packageName,
                            PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 检查字体
     */
    private static boolean checkFont() {
        String ttfUrl = utilPath + File.separator + PrintFont;
        File fontFile = new File(ttfUrl);
        return fontFile.isFile();
    }

    /**
     * 初始化安装提示
     */
    private static void InstallationTipsDialog(final Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("检测到您未安装打印组件，请先安装打印组件才可以正常打印!");
        builder.setTitle("安装提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                InstallationApp(context);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /**
     * 创建字体
     */
    private static BaseFont creatBaseFont() {
        try {
            String ttfUrl = utilPath + File.separator + PrintFont;
            return BaseFont.createFont(ttfUrl,
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 安装APK文件
     */
    private static void InstallationApp(final Context context) {
        try {
            // 安装字体、打印APK
            AssetsFileUtils.getInstance(context)
                    .copyAssetsToSD("print", "abeframe/print/utils")
                    .setFileOperateCallback(new AssetsFileUtils.FileOperateCallback() {
                        @Override
                        public void onSuccess() {
                            File mFile = new File(utilPath + File.separator + PrintAPK);
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.fromFile(mFile), "application/vnd.android.package-archive");
                            context.startActivity(intent);
                        }

                        @Override
                        public void onFailed(String error) {

                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}